package org.dromara.finance.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.finance.domain.PurchaseInvoiceList;
import org.dromara.finance.domain.bo.PurchaseInvoiceListBo;
import org.dromara.finance.domain.vo.PurchaseInvoiceListVo;
import org.dromara.finance.mapper.PurchaseInvoiceListMapper;
import org.springframework.stereotype.Service;
import org.dromara.finance.domain.bo.PurchaseInvoiceBo;
import org.dromara.finance.domain.vo.PurchaseInvoiceVo;
import org.dromara.finance.domain.PurchaseInvoice;
import org.dromara.finance.mapper.PurchaseInvoiceMapper;
import org.dromara.finance.service.IPurchaseInvoiceService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 采购发票Service业务层处理
 *
 * @author xxy
 * @date 2025-08-19
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PurchaseInvoiceServiceImpl implements IPurchaseInvoiceService {

    private final PurchaseInvoiceMapper baseMapper;
    private final PurchaseInvoiceListMapper purchaseInvoiceListMapper;

    /**
     * 查询采购发票
     *
     * @param id 主键
     * @return 采购发票
     */
    @Override
    public PurchaseInvoiceVo queryById(Long id){
        // 1. 查主表
        PurchaseInvoiceVo vo = baseMapper.selectVoById(id);
        if (vo == null) {
            return null;
        }

        // 2. 查子表
        List<PurchaseInvoiceListVo> children = purchaseInvoiceListMapper.selectVoList(
            new LambdaQueryWrapper<PurchaseInvoiceList>()
                .eq(PurchaseInvoiceList::getPurchaseInvoiceId, id)
        );

        // 3. 拼接进 VO
        vo.setPurchaseInvoiceList(children);
        return vo;
    }

    /**
     * 分页查询采购发票列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 采购发票分页列表
     */
    /*@Override
    public TableDataInfo<PurchaseInvoiceVo> queryPageList(PurchaseInvoiceBo bo, PageQuery pageQuery) {
        Page<PurchaseInvoiceVo> result = baseMapper.selectInvoiceList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }*/
    @Override
    public TableDataInfo<PurchaseInvoiceVo> queryPageList(PurchaseInvoiceBo bo, PageQuery pageQuery) {
        // 1. 分页查询主表，返回Page对象
        Page<PurchaseInvoiceVo> page = pageQuery.build();
        page = baseMapper.selectInvoiceList(page, bo);

        List<PurchaseInvoiceVo> mainList = page.getRecords();

        if (!mainList.isEmpty()) {
            // 2. 批量查询子表
            List<Long> mainIds = mainList.stream()
                .map(PurchaseInvoiceVo::getId)
                .collect(Collectors.toList());

            List<PurchaseInvoiceListVo> subList = baseMapper.selectInvoiceListByIds(mainIds);

            // 3. 按主表ID分组
            Map<Long, List<PurchaseInvoiceListVo>> subMap = subList.stream()
                .collect(Collectors.groupingBy(PurchaseInvoiceListVo::getPurchaseInvoiceId));

            // 4. 组装到主表对象
            mainList.forEach(main ->
                main.setPurchaseInvoiceList(subMap.getOrDefault(main.getId(), new ArrayList<>()))
            );
        }

        // 5. 把组装好的主表列表重新设置回分页对象
        page.setRecords(mainList);

        return TableDataInfo.build(page);
    }



    /**
     * 查询符合条件的采购发票列表
     *
     * @param bo 查询条件
     * @return 采购发票列表
     */
    @Override
    public List<PurchaseInvoiceVo> queryList(PurchaseInvoiceBo bo) {
        LambdaQueryWrapper<PurchaseInvoice> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PurchaseInvoice> buildQueryWrapper(PurchaseInvoiceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PurchaseInvoice> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(PurchaseInvoice::getId);
        lqw.eq(bo.getPurchaseContractId() != null, PurchaseInvoice::getPurchaseContractId, bo.getPurchaseContractId());
        return lqw;
    }

    /**
     * 新增采购发票
     *
     * @param bo 采购发票
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(PurchaseInvoiceBo bo) {
        // 1. 保存主表
        PurchaseInvoice add = MapstructUtils.convert(bo, PurchaseInvoice.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;

        if (flag) {
            // 设置回主表id
            bo.setId(add.getId());

            // 2. 处理子表集合
            List<PurchaseInvoiceListBo> items = bo.getPurchaseInvoiceList();
            if (items != null && !items.isEmpty()) {
                List<PurchaseInvoiceList> entityList = items.stream().map(item -> {
                    PurchaseInvoiceList entity = MapstructUtils.convert(item, PurchaseInvoiceList.class);
                    // 给子表设置主表id
                    entity.setPurchaseInvoiceId(add.getId());
                    return entity;
                }).collect(Collectors.toList());

                // 批量插入子表
                purchaseInvoiceListMapper.insertBatch(entityList);
            }
        }
        return flag;
    }

    /**
     * 修改采购发票
     *
     * @param bo 采购发票
     * @return 是否修改成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(PurchaseInvoiceBo bo) {
        // 1. 更新主表
        PurchaseInvoice update = MapstructUtils.convert(bo, PurchaseInvoice.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;

        if (flag) {
            Long invoiceId = bo.getId();

            // 2. 删除旧的子表
            purchaseInvoiceListMapper.delete(
                new LambdaQueryWrapper<PurchaseInvoiceList>()
                    .eq(PurchaseInvoiceList::getPurchaseInvoiceId, invoiceId)
            );

            // 3. 插入新的子表
            List<PurchaseInvoiceListBo> items = bo.getPurchaseInvoiceList();
            if (items != null && !items.isEmpty()) {
                List<PurchaseInvoiceList> entityList = items.stream().map(item -> {
                    PurchaseInvoiceList entity = MapstructUtils.convert(item, PurchaseInvoiceList.class);
                    entity.setPurchaseInvoiceId(invoiceId);
                    return entity;
                }).collect(Collectors.toList());

                // 批量插入
                purchaseInvoiceListMapper.insertBatch(entityList);
            }
        }

        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PurchaseInvoice entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除采购发票信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
